package com.tduck.cloud.api.web.controller.system;

import cn.hutool.core.map.MapUtil;
import com.tduck.cloud.common.entity.security.LoginUserEntity;
import com.tduck.cloud.common.entity.security.SysUserVO;
import com.tduck.cloud.security.service.SysLoginService;
import com.tduck.cloud.security.service.SysPermissionService;
import com.tduck.cloud.security.service.TokenService;
import com.tduck.cloud.system.request.LoginRequest;
import com.tduck.cloud.common.util.Result;
import com.tduck.cloud.system.entity.SysMenuEntity;
import com.tduck.cloud.system.entity.SysUserEntity;
import com.tduck.cloud.system.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录相关
 *
 * @author smalljop
 */
@RestController
@RequiredArgsConstructor
public class SysLoginController {
    private final SysLoginService loginService;

    private final SysMenuService menuService;

    private final SysPermissionService permissionService;

    private final TokenService tokenService;

    /**
     * 登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginBody) {
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        return Result.success(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Result
    getInfo(HttpServletRequest request) {
        LoginUserEntity loginUser = tokenService.getLoginUser(request);
        SysUserVO user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String, Object> result = MapUtil.newHashMap();
        result.put("user", user);
        result.put("roles", roles);
        result.put("permissions", permissions);
        return Result.success(result);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public Result getRouters(HttpServletRequest request) {
        LoginUserEntity loginUser = tokenService.getLoginUser(request);
        // 用户信息
        SysUserVO user = loginUser.getUser();
        List<SysMenuEntity> menus = menuService.getMenuTreeByUserId(user.getId());
        return Result.success(menuService.buildMenus(menus));
    }
}
